package com.study.utils;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class ConnectionUtils
{
    /**
     * 
     * @描述：获取mq的链接
     * @作者：严磊
     * @时间：2020年6月29日 下午8:11:01
     * @return
     * @throws TimeoutException 
     * @throws IOException 
     */
    public static Connection getConnection() throws IOException, TimeoutException 
    {
        //1、创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        
        //2、设置连接属性
        Map<String, String> config = ReadCofnigFileUtils.readProperties("rabbitmq.properties");
        
        factory.setHost(config.get("host"));
        factory.setPort(Integer.parseInt(config.get("port")));
        factory.setVirtualHost(config.get("virtualHost"));
        factory.setUsername(config.get("username"));
        factory.setPassword(config.get("password"));
        
        //3、网络故障自动连接恢复
        factory.setAutomaticRecoveryEnabled(true);
        
        //4、从工厂获取连接
        Connection connection = factory.newConnection();
        
        return connection;
    }
    
    public static void main(String[] args) throws IOException, TimeoutException
    {
        System.out.println(getConnection());
        
    }
}
